package com.root.dreameraadmin.adapter;

/**
 * Created by lijialin on 5/6/16.
 */

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.root.dreameraadmin.R;
import com.root.dreameraadmin.utils.AsyncImageLoader;

import java.util.List;


public class Myadapter extends BaseAdapter {
    private AsyncImageLoader asyncImageLoader;
    List<String> data, title_data;
    Context context;
    ImageView iv;
    TextView tv;
    private ListView listView;
    private static final String TAG="Myadapter";

    public Myadapter(Context context, List<String> list, List<String> title, ListView listView) {
        this.context = context;
        this.data = list;
        this.title_data = title;
        asyncImageLoader = new AsyncImageLoader();
        this.listView=listView;
        // TODO Auto-generated constructor stub
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position,  View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.picture_list_item,
                    null);
        }
//start
        iv = (ImageView) convertView.findViewById(R.id.picture);
        String url = data.get(position).toString();
        Log.d(TAG,"url is "+url);
        iv.setTag(url);



        Drawable cachedImage = asyncImageLoader.loadDrawable(url, new AsyncImageLoader.ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                if (imageViewByTag != null) {
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
        if (cachedImage == null) {
            iv.setImageResource(R.drawable.empty_photo);
        }else{
            iv.setImageDrawable(cachedImage);
        }


        //end
        tv = (TextView) convertView.findViewById(R.id.title);
        tv.setText(title_data.get(position).toString());
        return convertView;
    }
}
